#!/bin/bash
#*******************************************************************************
# Copyright (c) 2019 IBM Corporation and others.
#
# This program and the accompanying materials
# are made available under the terms of the Eclipse Public License 2.0
# which accompanies this distribution, and is available at
# https://www.eclipse.org/legal/epl-2.0/
#
# SPDX-License-Identifier: EPL-2.0
#
# Contributors:
#     Sravan Kumar Lakkimsetti - initial API and implementation
#*******************************************************************************

# USAGE: fn-write-property VAR_NAME
#   VAR_NAME: Variable name to write as "variable=value" form
# This script assumes the following variables have been defined and are pointing
# to an appropriate file (see master-build.sh):
# BUILD_ENV_FILE=${buildDirectory}/buildproperties.shsource
# BUILD_ENV_FILE_PHP=${buildDirectory}/buildproperties.php
# BUILD_ENV_FILE_PROP=${buildDirectory}/buildproperties.properties

# Note we always append to file, assuming if doesn't exist yet and will be
# created, and for each build, it won't exist, so will be written fresh for
# each build.

fn-write-property ()
{
  echo "export $1=$2" >> $BUILD_ENV_FILE
  echo "\$$1 = $2;" >> $BUILD_ENV_FILE_PHP
  echo "$1 = $2" >> $BUILD_ENV_FILE_PROP
}

# this function executes command passed as command line parameter and
# if that command fails it exit with the same error code as the failed command
fn-run-command ()
{
  $*
  returnCode=$?
  if [ $returnCode != 0 ]; then
    echo "Execution of \"$*\" failed with return code : $returnCode"
    exit $returnCode
  fi
}

fn-notarize-macbuild ()
{
	set -x
	BUILD_DIR="$1"; shift
	DMG="$1"; shift
	
	pushd $BUILD_DIR
		
	PRIMARY_BUNDLE_ID="$(echo ${DMG} | sed  's/-macosx-cocoa-x86_64.dmg//g')"
	
	RESPONSE=$(curl -s -X POST -F file=@${DMG} -F 'options={"primaryBundleId": "'${PRIMARY_BUNDLE_ID}'", "staple": true};type=application/json' http://172.30.206.146:8383/macos-notarization-service/notarize)
	  
	UUID=$(echo $RESPONSE | grep -Po '"uuid"\s*:\s*"\K[^"]+')
    STATUS=$(echo $RESPONSE | grep -Po '"status"\s*:\s*"\K[^"]+')
	
	while [[ ${STATUS} == 'IN_PROGRESS' ]]; do
	  sleep 1m
	  RESPONSE=$(curl -s http://172.30.206.146:8383/macos-notarization-service/${UUID}/status)
      STATUS=$(echo $RESPONSE | grep -Po '"status"\s*:\s*"\K[^"]+')
	done
	
	if [[ ${STATUS} != 'COMPLETE' ]]; then
	  echo "Notarization failed: ${RESPONSE}"
	  exit 1
	fi
	
	rm "${DMG}"
	
	curl -JO http://172.30.206.146:8383/macos-notarization-service/${UUID}/download
	popd
	set +x
}
